import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import weixinShare from '../../lib/weixinShare';
import { addErrorListener } from '../../lib/handleError';
import AJAX from '../../lib/ajax';
import weui from 'weui.js'
import Area from '../../lib/area'

import checkSubmit from './checkSubmit'

require('../../lib/rem');
require('../../styles/common.less');
require('./ReceiverInfo.less');
require('../../styles/iconfont/iconfont.css');

class ReceiverInfo extends Component {
  constructor(props) {
    super(props)
    this.receiverInfo = [];

    this.express = []; // 物流中心列表

    if (sessionStorage.getItem('receiverInfo')) { // 本地读取缓存信息
      this.receiverInfo = sessionStorage.getItem('receiverInfo').replace(/\s*/g, "").split('#')

      let i = 2
      while (i <= 5) {
        this.receiverInfo[i] = JSON.parse(this.receiverInfo[i])
        i++
      }
    }

    this.state = {
      isReady: false,     //是否可以加载页面

      name: this.receiverInfo[0] || '',
      phone: this.receiverInfo[1] || '',
      defaultProvince: [],
      defaultCity: [],
      defaultCounty: [],
      selectArea: this.receiverInfo.length > 4 ? {} : {color: '#999'},
      selectPres: {color: '#999'},
      expressTrue: false, // 是否可选物流中心
      expressAdd: this.receiverInfo.length > 4 ? this.receiverInfo[5] : [0, '请选择大学(校名校区等)'],
      defaultValue: 0,
    };
  }

  componentWillMount() {
    addErrorListener()()
    weixinShare.hideAll()
  }

  componentDidMount() {
    AJAX.appendBaiduAnalysis()

    this.fetchArea();
  }

  fetchArea() {
    Area(res => {
      const area = res;
      this.area = res;

      this.setState({
        defaultProvince: this.receiverInfo[2] || // 默认省
          [
            area[0].value,
            '请选择省市区'
          ],
        defaultCity: this.receiverInfo[3] || // 默认市
          [
            area[0].children[0].value,
            ''
          ],
        defaultCounty: this.receiverInfo[4] || // 默认区县
          [
            area[0].children[0].children[0].value,
            ''
          ],
        selectArea: this.receiverInfo.length > 4 ? {} : {color: '#999'},
        isReady: true, //是否可以加载页面
      }, () => {
        if (this.state.defaultProvince[1] && this.state.defaultCity[1] && this.state.defaultCounty[1]) {
          this.fetchLogis(1);
        }
      })
    });
  }

  selectAddress() {
    weui.picker(this.area,{
      className: 'custom-classname',
      container: 'body',

      id: 1, // 区分多个picker唯一标识

      defaultValue: [
        this.state.defaultProvince[0],
        this.state.defaultCity[0],
        this.state.defaultCounty[0]
      ],

      onConfirm: (result) => {
        this.setState({
          defaultProvince: [
            result[0].value,
            result[0].label
          ],

          defaultCity: [
            result[1].value,
            result[1].label
          ],

          defaultCounty: [
            result[2].value,
            result[2].label
          ],
          selectArea: {},
          expressAdd: [0, '请选择大学(校名校区等)'],
        }, () => {
          this.fetchLogis();
        })
      },
      title: '请选择省市区'
    })
  }

  fetchLogis(type) { // 获取物流中心
    const params = {
      code: this.state.defaultCounty[0]
    }

    AJAX.fetchGet("logisticsCenterList", params, (data) => {
      this.express = [
        {value: 0, label: '请选择'}
      ];

      if (data.length <= 0) {
        weui.alert('当前地区暂无可选物流中心', function () {
          console.log('ok')
        }, {
            title: '温馨提示'
        });

        this.setState({
          expressTrue: false,
          selectPres: {color: '#999'},
          expressAdd: [0, '请选择大学(校名校区等)']
        })

        return;
      }

       data.reduce((target, origin) => {
         this.express.push({
           value: parseInt(origin.code),
           label: origin.name
         })
       }, 0);

       let defalutEXP = [];
       let defaultValue = 0;

       if (type) { // 是初始化调用需要设置默认物流为本地存储的物流信息
         defalutEXP = this.receiverInfo.length > 4 ? this.receiverInfo[5] : [this.express[0].value, this.express[0].label];
         defaultValue = this.receiverInfo.length > 4 ? this.receiverInfo[5][0] : this.express[0].value
       } else {
         defalutEXP = [this.express[0].value, this.express[0].label];
         defaultValue = this.express[0].value
       }

       this.setState({
         selectPres: {},
         expressAdd: defalutEXP,
         defaultValue: defaultValue,
         expressTrue: true
       })
    })
  }

  selectExpress () {
    if (this.state.selectArea.color || !this.state.expressTrue) {
      weui.topTips('请先选择省市区');
      return;
    }
    
    const dateId = new Date().getTime()
    
    weui.picker(this.express, {
      className: 'custom-classname',
      container: 'body',
      id: dateId, // 区分多个picker唯一标识
      defaultValue: [this.state.defaultValue],

      // onClose: (result) => {
      //   this.setState({
      //     isChangeExpress: true
      //   })
      // },

      onConfirm: (result) => { // 确定
        this.setState({
          expressAdd: [result[0].value, result[0].label]
        })
      },
      title: '请选择大学'
    })
  }



  handleSubmit () { // 提交
    const name = this.refs.name.value
    const phone = this.refs.phone.value
    
    const returnRes = checkSubmit(name, phone)
    
    switch (returnRes[0]) {
      case 0:
        weui.topTips(returnRes[1]);
        return;
      case 1:
        if (!this.state.expressAdd[1] || this.state.expressAdd[0] == 0 || this.state.expressAdd[1] == '请选择大学(校名校区等)') {
          weui.topTips('请选择大学(校名校区等)');
          return;
        }
        const receiverInfo = `
          ${name}#
          ${phone}#
          ${JSON.stringify(this.state.defaultProvince)}#
          ${JSON.stringify(this.state.defaultCity)}#
          ${JSON.stringify(this.state.defaultCounty)}#
          ${JSON.stringify(this.state.expressAdd)}
        `
        sessionStorage.setItem('receiverInfo', receiverInfo)
        location.href="./SendExpress"
        return;
    }
  }

  render () {
    return (
      this.state.isReady &&

      <div className="senderInfo">
        <section className="card senderTitle">
          <span>收</span>
          <label>收件人信息</label>
        </section>

        <section className="card senderEdit">
          <ul>
            <li>
              <input type="text" ref="name"
                defaultValue={this.state.name}
                className="nameEdit"
                placeholder="姓名"
              />
              
              <input type="number" ref="phone"
                defaultValue={this.state.phone}
                className="phoneEdit"
                placeholder="电话"
              />
            </li>

            <li onClick={this.selectAddress.bind(this)}>
              <label style={this.state.selectArea}>{this.state.defaultProvince[1]} {this.state.defaultCity[1]} {this.state.defaultCounty[1]}</label>
              <span className="icon iconfont iconIcon_right"></span>
            </li>

            <li onClick={this.selectExpress.bind(this)}>
              <label style={this.state.selectPres}>{this.state.expressAdd[1]}</label>
              <span className="icon iconfont iconIcon_right"></span>
            </li>
          </ul>

          <button type="button"
            className="submitBtn"
            onClick={this.handleSubmit.bind(this)}
          >确定
          </button>
        </section>
      </div>
    )
  }
}
ReactDOM.render(<ReceiverInfo />, document.getElementById('app'));
if (module.hot) {
  module.hot.accept();
}